package com.example.ceramics.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.ceramics.R;
import com.example.ceramics.activity.DetailActivity;
import com.example.ceramics.database.dao.GoodsDaoImpl;
import com.example.ceramics.database.dao.IGoodsDao;
import com.example.ceramics.entity.GoodsEntity;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class GoodsOnlyOneFragment extends BaseFragment {

    private String title;
    private RefreshLayout refreshLayout;
    private ImageView ivImg;
    private IGoodsDao goodsDao;

    public GoodsOnlyOneFragment() {
    }

    public static GoodsOnlyOneFragment newInstance(String title) {
        GoodsOnlyOneFragment fragment = new GoodsOnlyOneFragment();
        fragment.title = title;
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_goods_only_one;
    }

    @Override
    protected void initView() {
        refreshLayout = mRootView.findViewById(R.id.refreshLayout);
        ivImg = mRootView.findViewById(R.id.iv_img);
    }

    @Override
    protected void initData() {
        goodsDao = new GoodsDaoImpl(mRootView.getContext());
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                refreshlayout.finishRefresh(1500/*,false*/);//传入false表示刷新失败
                localGoodsList();
                showToast("刷新成功！");
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                localGoodsList();
            }
        });
        localGoodsList();
    }

    private void localGoodsList() {
        List<GoodsEntity> list = goodsDao.listGoodsByType(title);
        GoodsEntity goodsEntity = new GoodsEntity();
        if (list.size()!=0) {
            goodsEntity = list.get(0);
            int img = goodsEntity.getGoodsImg();
            ivImg.setImageResource(img);
        }
        GoodsEntity finalGoodsEntity = goodsEntity;
        ivImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateTo(DetailActivity.class,"detail", finalGoodsEntity);
            }
        });
    }
}